<?php

namespace App\Imports;

use App\Models\Order;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Importable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;

class OrderImport implements ToCollection, WithChunkReading, ShouldQueue
{
	use Importable;
	
	public function collection(Collection $rows)
	{
		// remove headrow.
		unset($rows[0]);
		
		if (count($rows) <= 0) return;
		
		foreach ($rows as $row) {
			DB::transaction(function () use ($row) {
				$orderId = isset($row[0]) ? $row[0] : null;
				$orderNumber = isset($row[1]) ? $row[1] : null;
				$expressCode = isset($row[2]) ? $this->getExpressCode($row[2]) : null;
				$expressNumber = isset($row[3]) ? $row[3] : null;
				
				$order = Order::where('id', $orderId)->where('number', $orderNumber)->first();
				if ($expressCode and $expressNumber and $order) {
					
					$deliveryData = [
						'delivery_company' => $expressCode,
						'delivery_number' => $expressNumber,
					];
					$order->update([
						'delivery_status' => 'delivered',
						'delivery_data' => $deliveryData,
					]);
					$order->items()->update([
						'delivery_status' => 'delivered',
						'delivery_data' => $deliveryData,
					]);
				}
			});
			usleep(50);
		}
	}
	
	public function chunkSize(): int
	{
		return 100;
	}
	
	public function getExpressCode($nameOrCode)
	{
		$companies = config('express.companies');
		foreach ($companies as $code => $name) {
			if (empty($code)) continue;
			if ($code == $nameOrCode) {
				return $code;
			}
			if ($name == $nameOrCode) {
				return $code;
			}
		}
		return '';
	}
}
